class Solution:
    def patternMatching(self, pattern: str, value: str) -> bool:
        count_a = sum(1 for ch in pattern if ch == 'a') # 计算a出现的次数
        count_b = len(pattern) - count_a # 计算b出现的次数
        if count_a < count_b: # 保证a次数大于b次数，否则交换位置
            count_a, count_b = count_b, count_a
            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)
        
        if not value: # 如果字符串为空，只有a字符串，返回真，否则返回假
            return count_b == 0
        if not pattern: # 如果匹配串为空，返回假
            return False
        
        for len_a in range(len(value) // count_a + 1): # 枚举a的长度
            rest = len(value) - count_a * len_a # b的总长度
            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):
                len_b = 0 if count_b == 0 else rest // count_b #计算出b的长度
                pos, correct = 0, True 
                value_a, value_b = None, None
                for ch in pattern:
                    if ch == 'a': 
                        sub = value[pos:pos+len_a] # 匹配a
                        if not value_a: # 第一次提取
                            value_a = sub
                        elif value_a != sub: # 后续匹配失败
                            correct = False
                            break
                        pos += len_a # 继续匹配
                    else:
                        sub = value[pos:pos+len_b] # 匹配b
                        if not value_b:# 第一次提取
                            value_b = sub
                        elif value_b != sub: # 后续匹配失败
                            correct = False
                            break
                        pos += len_b # 继续匹配
                if correct and value_a != value_b: # 保证a和b不相等
                    return True
        
        return False

